using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;
namespace DemoGame1
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class myGame : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        public int choice = 1;
        public Vector2 choice_pos = new Vector2(-85, -250);
        public int width = 0;
        public int height = 0;
        Rectangle myrect = new Rectangle(50, 50, 1024 - 100, 600 - 100);
        /*Map map;
   
        Player player;
        Player p2;
        My2DSprite skillfinal;
        public int range = 200;
        public float SPEED = 30.0f;
        public int skilling = -1;
        */

        //thaitujim
        public static CurrentScreen currentScreen;
        StartMenu startMenu;
        ChooseCharacter chooseCharacter;
        Setting setting;
        Guide guide;
        Credit credit;
        public static MediaControler mediaControler;

        public static int preferredBackBufferWidth = 1000;
        public static int preferredBackBufferHeight = 650;
        public static Global.THEMES theme = Global.THEMES.KEN_THEME;
        protected SpriteFont _spriteFont;
        //thaitujim

        public static Playscreen playscreen;
        public myGame()
        {
            Global.game1 = this;
            this.IsMouseVisible = true;
            this.TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 90);
            this.Window.Title = "Warrior";
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            width = graphics.PreferredBackBufferWidth = preferredBackBufferWidth;
            height = graphics.PreferredBackBufferHeight = preferredBackBufferHeight;
            graphics.PreferMultiSampling = false;
            //graphics.IsFullScreen = true;
            Window.AllowUserResizing = false;

            // Subscribe to the game window's ClientSizeChanged event.
            // Window.ClientSizeChanged += new EventHandler(Window_ClientSizeChanged);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        ///      

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here


            base.Initialize();

        }


        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        /// 


        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            //     player = new Player(Content, "Ryu", new Vector2(0, 0), new Vector2(62, 102));
            //      p2 = new Player(Content, "Ryu", new Vector2(500, 0), new Vector2(62, 102));
            //     map = new Map(Content, "backgroundgame", new Vector2(0, 0), new Vector2(2048, 1200));
            Texture2D[] t = new Texture2D[1];
            t[0] = Content.Load<Texture2D>("ryufinal");

            //     skillfinal = new My2DSprite(t, Vector2.Zero);
            // TODO: use this.Content to load your game content here

            // When finish project
            //   playscreen = new Playscreen(this, 1, "Ryu");
           //   playscreen = new Playscreen(this, 1, "Ken");

            //thaitujim
            XmlDocument doc = new XmlDocument();
            doc.Load(XMLDataProvider.strData);
            XmlElement settingXML = (XmlElement)doc.SelectSingleNode("//Setting");
            foreach (XmlElement set in settingXML.ChildNodes)
            {
                if (set.Name == "Theme")
                {
                    if (Convert.ToInt16(set.InnerText.Trim()) == 0)
                    {
                        myGame.theme = Global.THEMES.RYU_THEME;
                    }

                    if (Convert.ToInt16(set.InnerText.Trim()) == 1)
                    {
                        myGame.theme = Global.THEMES.KEN_THEME;
                    }
                }
            }

            mediaControler = new MediaControler(Content);
            mediaControler.LoadMusicTheme(0);
            InitMenu();
            setting.LoadSetting();

            string strFont = "Menu/menuFont";
            _spriteFont = Content.Load<SpriteFont>(strFont);
            //thaitujim

            // playscreen = new Playscreen(this, 1, "Ken");
        }

        public void InitMenu()
        {
            String strStartMenu = String.Empty;
            String strChooseCharacter = String.Empty;
            String strSetting = String.Empty;
            String strCredits = String.Empty;
            String strGuide = String.Empty;
            String strHighScore = String.Empty;

            if (theme == Global.THEMES.KEN_THEME)
            {
                strStartMenu = XMLDataProvider.KENTHEME.strStartMenu;
                strChooseCharacter = XMLDataProvider.KENTHEME.strChooseCharacter;
                strSetting = XMLDataProvider.KENTHEME.strSetting;
                strCredits = XMLDataProvider.KENTHEME.strCredits;
                strGuide = XMLDataProvider.KENTHEME.strGuide;
                strHighScore = XMLDataProvider.KENTHEME.strHighScore;
            }
            if (theme == Global.THEMES.RYU_THEME)
            {
                strStartMenu = XMLDataProvider.RYUTHEME.strStartMenu;
                strChooseCharacter = XMLDataProvider.RYUTHEME.strChooseCharacter;
                strSetting = XMLDataProvider.RYUTHEME.strSetting;
                strCredits = XMLDataProvider.RYUTHEME.strCredits;
                strGuide = XMLDataProvider.RYUTHEME.strGuide;
                strHighScore = XMLDataProvider.RYUTHEME.strHighScore;
            }

            startMenu = new StartMenu(this, strStartMenu);
            chooseCharacter = new ChooseCharacter(this, strChooseCharacter);
            if (setting == null)
            {
                setting = new Setting();
            }
            setting.LoadReSource(this, strSetting);
            guide = new Guide(this.Content, strGuide);
            credit = new Credit(this, strCredits);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 

        protected override void Update(GameTime gameTime)
        {

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            KeyboardState newState = Keyboard.GetState();

            MouseState ms = Mouse.GetState();
            if (ms.LeftButton == ButtonState.Pressed)
            {
                //Click vao nhan vat thi exit
                //   if (mb.IsClicked(new Vector2(ms.X, ms.Y)))
                //         Exit();
            }
            //playscreen.Update(gameTime, newState);

            // TODO: Add your update logic here
            //thaitujim
            switch (currentScreen)
            {
                case CurrentScreen.StartMenu:
                    mediaControler.LoadMusicTheme(0);
                    startMenu.Update(gameTime);
                    break;

                case CurrentScreen.ChooseCharacter:
                    chooseCharacter.Update(gameTime);
                    break;

                case CurrentScreen.Setting:
                    setting.Update(gameTime);
                    break;

                case CurrentScreen.Guide:
                    guide.Update(gameTime);
                    break;

                case CurrentScreen.Credit:
                    credit.Update(gameTime);
                    break;

                case CurrentScreen.InGame:
                    if (newState.IsKeyDown(Keys.Escape))
                    {
                        this.Exit();
                    }

                    if (newState.IsKeyDown(Keys.Enter))
                    {
                        //mediaControler.PlaySoundEffect(MediaControler.BUSHA);
                    }

                    playscreen.Update(gameTime, newState);
                    if (playscreen.IsClear())
                    {
                        if (playscreen.Stage != Playscreen.FINAL_STAGE)
                        {
                            playscreen = new Playscreen(this, playscreen.Stage + 1, playscreen.player.charactername);
                            SaveGame(playscreen.Stage.ToString(), playscreen.player.charactername);
                        }
                        
                    }

                    break;
            }
            mediaControler.PlayMusicTheme();
            mediaControler.Update(gameTime);
            //thaitujim


            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            // TODO: Add your drawing code here
            spriteBatch.Begin();
            //thaitujim
            switch (currentScreen)
            {
                case CurrentScreen.StartMenu:
                    startMenu.Draw(spriteBatch, gameTime);
                    break;

                case CurrentScreen.ChooseCharacter:
                    chooseCharacter.Draw(spriteBatch, gameTime);
                    break;

                case CurrentScreen.Setting:
                    setting.Draw(spriteBatch, gameTime);
                    break;

                case CurrentScreen.Guide:
                    guide.Draw(spriteBatch, gameTime);
                    break;

                case CurrentScreen.Credit:
                    credit.Draw(spriteBatch, gameTime);
                    break;

                case CurrentScreen.Exit:
                    this.Exit();
                    break;

                case CurrentScreen.InGame:
                    playscreen.Showscreen(spriteBatch, gameTime);
                    break;
            }
            //thaitujim

            //spriteBatch.DrawString(_spriteFont, mediaControler.MusicPlayerState(), Vector2.Zero, Color.White);
            //playscreen.Showscreen(spriteBatch, gameTime);

            spriteBatch.End();
            base.Draw(gameTime);
        }



        public void OnEvent(Global.EVENTS eventID, object sender, object arg)
        {
            if (eventID == Global.EVENTS.GM_CHARACTER_CHOSEN)
            {
                playscreen = new Playscreen(this, 1, (string)arg);
            }
            if (eventID == Global.EVENTS.GM_CONTINUE_GAME)
            {

                currentScreen = CurrentScreen.InGame;
                XmlDocument doc = new XmlDocument();
                doc.Load(XMLDataProvider.strContinue);
                XmlElement elm = (XmlElement)doc.SelectSingleNode("//Charactername");
                String Charactername = elm.InnerText;
                elm = (XmlElement)doc.SelectSingleNode("//Stage");
                String stage = elm.InnerText;
                playscreen = new Playscreen(this, Int32.Parse(stage), Charactername);
            }
        }


        public static void SaveGame(String stage, String charactername)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(XMLDataProvider.strContinue);
            XmlElement elmname = (XmlElement)doc.SelectSingleNode("//Charactername");
            elmname.InnerText = charactername;

            XmlElement elmstage = (XmlElement)doc.SelectSingleNode("//Stage");
            elmstage.InnerText = stage;

            doc.Save(XMLDataProvider.strContinue);
        }

    }
}
